package com.project.web.wechat.controller.app;

import com.project.common.core.utils.exception.CustomException;
import com.project.common.core.utils.exception.RESP_CODE_ENUM;
import com.project.common.core.utils.exception.Result;
import com.project.common.core.utils.weChat.WeChatUtil;
import com.project.web.wechat.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信公众号服务API
 *
 * @Author: wyy
 * @Date: 2020-04-08 13:00
 */
@Api(tags = "微信公众号服务API")
@RestController("weChatMpController")
@RequestMapping("/weChat/mp")
public class WeChatMpController extends BaseController {
    public static final Logger log = LoggerFactory.getLogger(WeChatMpController.class);

    /**
     * 根据网页授权code换取openId
     *
     * @param code 网页授权code
     * @return
     */
    @ApiOperation(value = "根据网页授权code换取openId")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "code", value = "网页授权code", dataType = "String", required = true)
    })
    @PostMapping(value = "/getOauth2AccessToken")
    public Result<JSONObject> test(String code) {
        log.info("code:\r\n{}",code);
        if (StringUtils.isBlank(code)) {
            throw new CustomException(RESP_CODE_ENUM.MISS_PARAMETER);
        }
        JSONObject oauth2AccessToken = WeChatUtil.getOauth2AccessToken(code);
        log.info("oauth2AccessToken:\r\n{}",oauth2AccessToken.toString());
        return getResult(oauth2AccessToken);
    }

    /**
     * 根据重定向地址及state参数生成网页授权链接
     *
     * @param redirectUri 重定向地址
     * @param state       网页授权参数
     * @return
     */
    @ApiOperation(value = "根据重定向地址及state参数生成网页授权链接")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "redirectUri", value = "网页授权重定向地址", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "state", value = "网页授权State参数", dataType = "String", required = true)
    })
    @PostMapping(value = "/getOauth2UrlOfBase")
    public Result<String> getOauth2UrlOfBase(String redirectUri, String state) {
        String webAuthUrl = WeChatUtil.getOauth2UrlOfBase(state, redirectUri);
        return getResult(webAuthUrl);
    }
}
